import pandas as pd
import numpy as np
from sklearn import preprocessing
import os
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN

import numpy as np
import matplotlib

import matplotlib.pyplot as plt

import matplotlib.colors

current_dir = os.path.dirname(__file__)



data = pd.read_csv(os.path.join(current_dir, 'Clustering.csv'))  # 加载csv格式的数据

X1=data['trestbps']
X2=data['thalach']
def DBScan_plot():
    matplotlib.use('Agg')
    # # 创建Figure
    fig = plt.figure()
    # 用来正常显示中文标签
    matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
    # 用来正常显示负号
    matplotlib.rcParams['axes.unicode_minus'] = False
    matplotlib.rcParams['figure.figsize'] = 5, 4

    X=np.vstack((X1,X2)).T
    X = preprocessing.scale(X)
    X = pd.DataFrame(X)
    res = []
    for eps in np.arange(0.001 , 1 , 0.05):
        for min_samples in range(2,10):
            dbscan = DBSCAN(eps = eps , min_samples = min_samples)
            dbscan.fit(X)
            n_clusters = len([i for i in set(dbscan.labels_) if i != -1])
            outliners = np.sum(np.where(dbscan.labels_ == -1 , 1 , 0))
            res.append({'eps':eps , 'min_samples':min_samples , 'n_clusters':n_clusters , 'outliners':outliners })
    df = pd.DataFrame(res)

    df.loc[df.n_clusters == 2, :]
    y_pred = DBSCAN(eps=0.5, min_samples=25, algorithm='ball_tree', metric='euclidean').fit_predict(X)
    plt.scatter(X[0], X[1], c=y_pred)
    plt.xlabel('trestbps')
    plt.ylabel('thalach')
    plt.title(u'DBSCAN聚类')
    plt.savefig(os.path.join(current_dir,"DBScan.png"))
    # plt.show()
    return "DBScan.png"

#Kmeans
def Kmeans_plot():
    matplotlib.use('Agg')
    # # 创建Figure
    fig = plt.figure()
    # 用来正常显示中文标签
    matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
    # 用来正常显示负号
    matplotlib.rcParams['axes.unicode_minus'] = False
    matplotlib.rcParams['figure.figsize'] = 5, 4
    plt.scatter(data['trestbps'], data['thalach'])  # 绘制原始数据

    kmeans = KMeans(n_clusters=4)  # 创建一个K-均值聚类对象
    kmeans.fit(data)  # 拟合算法
    cluster_assignment = kmeans.predict(data)  # 获取聚类分配
    plt.scatter(data['trestbps'], data['thalach'], c=cluster_assignment)  # 绘制聚类结果
    cluster_assignment = cluster_assignment.astype(str) #聚类分配，重新设置类别颜色
    cluster_assignment[cluster_assignment == '0'] = 'b'
    cluster_assignment[cluster_assignment == '1'] = 'g'
    cluster_assignment[cluster_assignment == '2'] = 'r'
    cluster_assignment[cluster_assignment == '3'] = 'y'
    plt.scatter(data['trestbps'], data['thalach'], c=cluster_assignment) #绘制聚类结果
    plt.xlabel('trestbps')
    plt.ylabel('thalach')
    plt.title(u'Kmeans聚类')
    plt.savefig(os.path.join(current_dir,"Kmeans.png"))
    # plt.show()
    return "Kmeans.png"


# DBScan_plot()
# Kmeans_plot()